Bad weather Kelheim Demo

Oleksandr Soboliev

Data

Data is taken from these resources:

Regression analysis resources

Analysis was proceeded using this statistical sources:

Importing and preparing data

Main target is to get result table containing all “expected” relevant data/variables that can be connected with changes of demand in Kelheim region, thus mobility data is collected on daily basis, remaining data has to be daily based.

After obtaining such table it would be useful(in sense of building a model and understanding the data) to check correlations between individual independent variable to dependent mobility variable. So the next chapter has a focus on filtering out unrelevant data to pass it to the model.

##Modify and join data

# Weatherstack
weatherstack_kelheim_daily = weatherstack_kelheim %>%
  group_by(date) %>%
  count(description)

# Stringency 
deu_stringency = json[grep("DEU.stringency_actual",names(json))]
date_stringency = sapply(strsplit(names(deu_stringency),split = ".",fixed = TRUE),"[[",2)
df_stringency = data.frame(date = date_stringency,stringency = deu_stringency)
df_stringency = df_stringency %>% mutate(stringency = as.numeric(stringency), date = as.Date(date))



# Ingolstadt
type_of_weather = unique(weatherstack_kelheim$description)
map_vector <- c("Clear","Sunny","Cloudy","Light","Light","Light","Light","Light","Light","Light","Light","Medium","Cloudy","Light","Light","Heavy","Heavy","Heavy","Light","Medium","Heavy","Heavy","Light","Heavy","Heavy","Heavy","Heavy","Heavy","Heavy","Light","Medium","Medium","Light","Heavy","Light","Light","Light","Light","Light","Heavy","Light","Medium","Heavy","Heavy","Heavy")
names(map_vector)<- type_of_weather




ingolstadt_weather = ingolstadt_weather %>% 
  mutate(season = ifelse(month(date) %in% c(12,1,2),"winter",NA)) %>%
  mutate(season = ifelse(month(date) %in% c(3,4,5),"spring",season)) %>%
  mutate(season = ifelse(month(date) %in% c(6,7,8),"summer",season)) %>%
  mutate(season = ifelse(month(date) %in% c(9,10,11),"autumn",season))# %>% dplyr::select(-tsun)




day_description_impact = weatherstack_kelheim_daily %>% pivot_wider(names_from = description,values_from = n)

#remove NAs
day_description_impact[is.na(day_description_impact)] = 0

day_description_impact = day_description_impact %>% pivot_longer(cols = all_of(type_of_weather),names_to = "description",values_to = "value")

day_description_impact = day_description_impact
day_description_impact$description = map_vector[(day_description_impact$description)]

day_description_impact= day_description_impact %>% group_by(date)%>%
  top_n(n = 1,value) %>% group_by(date) %>% top_n(n = 1,description) %>% rename(weather_impact = value)

#####Join the data#####

result_data = demand %>% inner_join(day_description_impact, by = "date") %>% inner_join(ingolstadt_weather,by = "date") %>% inner_join(df_stringency,by = "date") %>% mutate(date = as.Date(date,format = "%Y-%m-%d"))
#Also need to be added weekday
result_data = result_data %>% mutate(wday = as.character(wday(date,week_start = 1)))

#Append holidays
result_data = result_data %>% left_join(df_holidays, by = "date") %>% replace_na(list(isHoliday = FALSE,snow = 0)) #%>% filter(noRides != 0) #%>% filter(date <"2021-07-01")

head(result_data)

From following plots we can see strong correlation between day of the week and number of Rides, because we want to simulate common day using MatSim it was decided to filter weekends out of resulting dataset for the model. Also because day doesn’t represent weather impact, like holidays that have strong impact on mobility so they are also excluded. First 4 days are excluded, because they have 0 rides due to KeXi service start.

wday_plot = ggplotly(ggplot(result_data)+
  geom_boxplot(aes(x = wday,y = noRides)))

holiday_plot = ggplotly(ggplot(result_data)+
  geom_boxplot(aes(x = isHoliday,y = noRides )))

annotations = list( 
  list( 
     x = 0.2,  
    y = 1.0,  
    text = "Weekday",  
    xref = "paper",  
    yref = "paper",  
    xanchor = "center",  
    yanchor = "bottom",  
    showarrow = FALSE 
  ),  
  list( 
     x = 0.75,  
    y = 1.0,  
    text = "Is Holiday",  
    xref = "paper",  
    yref = "paper",  
    xanchor = "center",  
    yanchor = "bottom",  
    showarrow = FALSE 
  ))

subplot(wday_plot,holiday_plot) %>% layout(annotations = annotations)
result_data = result_data %>% filter(wday!=6 & wday!=7,isHoliday == FALSE, noRides!=0)

After first data processing it would be helpful to find some dependencies in the data using scatter plots mapped to number of rides. Here is summary of end dataset

result_data$description = factor(result_data$description)
result_data$season = factor(result_data$season)
result_sum  = data.frame(c("noRides","description","tavg","tmin","tmax","prcp","snow","wspd","wpgt","pres","tsun"),c("Number of rides in day (dependent variable)","Weather description","The average air temperature in °C","The minimum air temperature in °C ","The maximum air temperature in °C","The daily precipitation total in mm","The maximum snow depth in mm","The average wind speed in km/h","The peak wind gust in km/h","The average sea-level air pressure in hPa","The daily sunshine total in minutes (m)"))
colnames(result_sum) = c("Variable","Description")
knitr::kable(result_sum)
Variable Description
noRides Number of rides in day (dependent variable)
description Weather description
tavg The average air temperature in °C
tmin The minimum air temperature in °C
tmax The maximum air temperature in °C
prcp The daily precipitation total in mm
snow The maximum snow depth in mm
wspd The average wind speed in km/h
wpgt The peak wind gust in km/h
pres The average sea-level air pressure in hPa
tsun The daily sunshine total in minutes (m)

Finding patterns using graphic approach

tavg_plot = ggplotly(
  ggplot(result_data)+
    geom_point(aes(y= noRides,x = tavg,colour = season))
  )%>%layout(xaxis = list(title = 'tavg'), yaxis = list(title = 'noRides'))


pres_plot= ggplotly(
  ggplot(result_data)+
    geom_point(aes(y= noRides,x = pres,colour = season))
  
  )%>%
  layout(xaxis = list(title = 'pres'), yaxis = list(title = 'noRides'))
prcp_plot = ggplotly(
  ggplot(result_data %>% filter(prcp!=0))+
    geom_point(aes(y= noRides,x = prcp,colour = season))
  )%>%
  layout(xaxis = list(title = 'prcp'), yaxis = list(title = 'noRides'))
snow_plot = ggplotly(
  ggplot(result_data %>% filter(snow!=0))+
    geom_point(aes(y= noRides,x = snow,colour = season))
  )%>% layout(xaxis = list(title = 'snow'), yaxis = list(title = 'noRides'))

anno = list( 
  list( 
     x = 0.2,  
    y = 1.0,  
    text = "noRides from avg temp",  
    xref = "paper",  
    yref = "paper",  
    xanchor = "center",  
    yanchor = "bottom",  
    showarrow = FALSE 
  ),  
  list( 
     x = 0.75,  
    y = 1.0,  
    text = "noRides from avg pressure",  
    xref = "paper",  
    yref = "paper",  
    xanchor = "center",  
    yanchor = "bottom",  
    showarrow = FALSE 
  ),
  list( 
     x = 0.2,  
    y = 0.4,  
    text = "noRides from avg precipitation",  
    xref = "paper",  
    yref = "paper",  
    xanchor = "center",  
    yanchor = "bottom",  
    showarrow = FALSE 
  ),
  list( 
     x = 0.75,  
    y = 0.4,  
    text = "noRides from avg snow depth",  
    xref = "paper",  
    yref = "paper",  
    xanchor = "center",  
    yanchor = "bottom",  
    showarrow = FALSE 
  ))

subplot(tavg_plot,pres_plot,prcp_plot,snow_plot,nrows = 2,titleY = TRUE,titleX = TRUE,margin = 0.1) %>% layout(annotations =anno)

After looking at these plots we can barely see existing strong dependencies or clusters, but there is one conspicious fact, that only during summer number of rides falls under ~50 while other seasons have more than 50 rides.

Finding correlations

Correlation coefficients between two variables we calculate using cor() function, later anova oneway test will be used for testing to check categorical variable dependency.

best_pred <- result_data %>% ungroup() %>%
  dplyr::select(-noRides,-description ,-date,-season,-noRequests,-avgEuclidianDistance_m,-avgTravelTime_s,-wday) %>%
  map_dbl(cor,y = result_data$noRides) %>%
  #map_dbl(abs) %>%
  sort(decreasing = TRUE) 
print(best_pred)
##           pres           wspd           snow           wpgt           wdir           prcp weather_impact 
##     0.20024096     0.15797184     0.07989549     0.06540688    -0.01914552    -0.03980433    -0.24434402 
##     stringency           tmin           tmax           tavg 
##    -0.27030542    -0.37968359    -0.39256927    -0.40748139

As a result highest absolute score in correlation have temperature(max during a day), snow(depth in mm), pressure(air pressure in hPa), stringency(strictness of covid19 policy), weather impact(highest hours of same description a day).

Testing of null hypothesis is made for dependent noRides and independent season, description and wday

season_test = oneway.test(result_data$noRides~result_data$season)$p.value
description_test = oneway.test(result_data$noRides~result_data$description)$p.value
wday_test = oneway.test(result_data$noRides~result_data$wday)$p.value
print(c("season" =season_test,"description" =description_test,"wday" =wday_test))
##       season  description         wday 
## 5.773598e-11 5.078272e-09 8.905504e-01

From the p-value we can see that null hypothesis can only be rejected for wday (p.value higher than 0.05), for the description and season we can’t make such conclusion. But one thing that should be also tested is dependency between seasons and temperature - 3.0760408^{-88}. As we can see temperature dependent from season, so in our future model one of the variable should be dropped.

Building a model

After determination of significant variables we can build different models using different set of variables, one thing remains same - first approach is to build linear model to make predictions, also to check which predictors impact number of rides most. In our approach we will firstly larger model using all relevant variables from previous chapter, then we reduce number of variables taking smaller subset and synchronous to check how model quality changes.

data = result_data

omega_model = lm(noRides ~ tavg+pres+stringency+snow+weather_impact*description,data = data)

summary(omega_model)
## 
## Call:
## lm(formula = noRides ~ tavg + pres + stringency + snow + weather_impact * 
##     description, data = data)
## 
## Residuals:
##    Min     1Q Median     3Q    Max 
## -59.45 -17.82  -0.96  17.06  71.97 
## 
## Coefficients:
##                                   Estimate Std. Error t value Pr(>|t|)    
## (Intercept)                      150.24137  188.33370   0.798    0.426    
## tavg                              -1.71969    0.23112  -7.441 6.87e-13 ***
## pres                               0.04581    0.17791   0.257    0.797    
## stringency                        -0.96741    0.12464  -7.762 8.01e-14 ***
## snow                               0.26878    0.43369   0.620    0.536    
## weather_impact                    -1.41658    5.27962  -0.268    0.789    
## descriptionCloudy                -24.62781   55.54216  -0.443    0.658    
## descriptionHeavy                 -24.55593   59.43501  -0.413    0.680    
## descriptionLight                 -38.12186   55.51521  -0.687    0.493    
## descriptionMedium                -39.67699   64.35116  -0.617    0.538    
## descriptionSunny                 -12.81980   62.00468  -0.207    0.836    
## weather_impact:descriptionCloudy   0.56846    5.29813   0.107    0.915    
## weather_impact:descriptionHeavy    1.33559    5.73935   0.233    0.816    
## weather_impact:descriptionLight    1.98662    5.31491   0.374    0.709    
## weather_impact:descriptionMedium   2.29055    6.58750   0.348    0.728    
## weather_impact:descriptionSunny    0.89311    5.85482   0.153    0.879    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 26.76 on 376 degrees of freedom
## Multiple R-squared:  0.3648, Adjusted R-squared:  0.3395 
## F-statistic:  14.4 on 15 and 376 DF,  p-value: < 2.2e-16

Low adjusted R^2 doesn’t tells that our model doesn’t fit the data. Let’s take a look on predicted values and residuals.

colors = c("actual" = "blue","predicted" = "red","residuals" = "gray50","zerorides" = "purple")
model = omega_model
test_data = data %>% add_predictions(model = model) %>% add_residuals(model = model) %>% mutate(error = ifelse(abs(resid)>=20,"extreme","normal"))


ggplotly(ggplot(test_data %>% filter(year(date)>=2020)) +
  geom_point(aes(x = date,y = noRides,color = "actual"))+
  geom_point(aes(x = date,y = pred,color = "predicted"))+
  scale_color_manual(values = colors)+
  ggtitle("Model fit without date"))
ggplotly(ggplot(test_data %>% filter(year(date)>=2020))+
            geom_line(aes(x = date,y = resid,color = "residuals"))+
            geom_ref_line(h = 0)+
            scale_color_manual(values = colors)+
            ggtitle("Residuals"))

As we can see from our residuals plot our data has continuous growing trend, that our model doesn’t consider, so taking a date variable to model can drastically improve model “quality”.

omega_date_model = lm(noRides ~ tavg+pres+stringency+snow+weather_impact*description+date+season,data = data)

summary(omega_date_model)
## 
## Call:
## lm(formula = noRides ~ tavg + pres + stringency + snow + weather_impact * 
##     description + date + season, data = data)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -81.140  -8.518  -0.047   9.677  39.403 
## 
## Coefficients:
##                                    Estimate Std. Error t value Pr(>|t|)    
## (Intercept)                      -2.272e+03  1.475e+02 -15.403  < 2e-16 ***
## tavg                             -2.930e-01  2.145e-01  -1.366   0.1727    
## pres                             -2.143e-01  1.063e-01  -2.015   0.0446 *  
## stringency                       -1.437e-01  9.473e-02  -1.517   0.1301    
## snow                              1.366e-01  2.569e-01   0.532   0.5951    
## weather_impact                    1.095e+00  3.145e+00   0.348   0.7279    
## descriptionCloudy                 8.749e+00  3.299e+01   0.265   0.7910    
## descriptionHeavy                  3.570e+00  3.560e+01   0.100   0.9202    
## descriptionLight                  5.374e+00  3.297e+01   0.163   0.8706    
## descriptionMedium                 3.544e+00  3.822e+01   0.093   0.9262    
## descriptionSunny                 -1.479e+00  3.687e+01  -0.040   0.9680    
## date                              1.383e-01  5.475e-03  25.256  < 2e-16 ***
## seasonspring                     -3.310e+00  3.133e+00  -1.056   0.2914    
## seasonsummer                     -1.162e+01  2.943e+00  -3.950 9.36e-05 ***
## seasonwinter                     -4.304e+00  2.959e+00  -1.455   0.1466    
## weather_impact:descriptionCloudy -1.503e+00  3.157e+00  -0.476   0.6342    
## weather_impact:descriptionHeavy  -7.195e-01  3.447e+00  -0.209   0.8348    
## weather_impact:descriptionLight  -1.610e+00  3.166e+00  -0.508   0.6114    
## weather_impact:descriptionMedium -1.560e+00  3.915e+00  -0.398   0.6905    
## weather_impact:descriptionSunny  -7.871e-01  3.484e+00  -0.226   0.8214    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 15.78 on 372 degrees of freedom
## Multiple R-squared:  0.7814, Adjusted R-squared:  0.7702 
## F-statistic: 69.97 on 19 and 372 DF,  p-value: < 2.2e-16
colors = c("actual" = "blue","predicted" = "red","residuals" = "gray50","zerorides" = "purple")
model = omega_date_model
test_data = data %>% add_predictions(model = model) %>% add_residuals(model = model) %>% mutate(error = ifelse(abs(resid)>=20,"extreme","normal"))

ggplotly(ggplot(test_data %>% filter(year(date)>=2020)) +
  geom_point(aes(x = date,y = noRides,color = "actual"))+
  geom_point(aes(x = date,y = pred,color = "predicted"))+
  scale_color_manual(values = colors)+
  ggtitle("Model fit with date"))
ggplotly(ggplot(test_data %>% filter(year(date)>=2020))+
            geom_line(aes(x = date,y = resid,color = "residuals"))+
            geom_ref_line(h = 0)+
            scale_color_manual(values = colors)+
            ggtitle("Residuals"))

As expected R^2 squared increased as well residual standard error is decreased to a number of 15,99. ~0.7 of R-squared is relatively high in weather statistics. To check correctness of used approach residuals have to be normally distributed.

Residuals histogram

barplot <- ggplot(test_data, aes(x = resid ))+
  geom_histogram(aes(y = stat(density)),colour="black", fill="white", binwidth=7)+
  ggtitle("Omega model residuals")

ggplotly(barplot)
normal_dist = fitdistrplus::fitdist(test_data$resid,"norm")
plot(normal_dist)

Reducing a model

Let’s take some variables out and see how model performs on the data and F Statistics. Low correlating variables from “Finding correlations” chapter are snow, stringency and weather_impact multiplied by description. Also there is strong correlation between average temperature and a season so our new model should contain only 1 of the predictors, because temperature have most impact on mobility and more large-scaled (season contains only 4 factors) we will take season out from new reduced_model.

reduced_1_model = lm(noRides ~ tavg+pres+stringency+snow+weather_impact*description+date,data = data)

summary(reduced_1_model)
## 
## Call:
## lm(formula = noRides ~ tavg + pres + stringency + snow + weather_impact * 
##     description + date, data = data)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -82.180  -9.343   0.017   9.964  37.716 
## 
## Coefficients:
##                                    Estimate Std. Error t value Pr(>|t|)    
## (Intercept)                      -2.224e+03  1.458e+02 -15.256  < 2e-16 ***
## tavg                             -7.192e-01  1.442e-01  -4.989 9.31e-07 ***
## pres                             -1.887e-01  1.073e-01  -1.759 0.079374 .  
## stringency                       -2.854e-01  7.940e-02  -3.595 0.000368 ***
## snow                              8.378e-02  2.606e-01   0.321 0.748064    
## weather_impact                   -2.558e-02  3.172e+00  -0.008 0.993571    
## descriptionCloudy                -9.663e-01  3.338e+01  -0.029 0.976922    
## descriptionHeavy                 -6.517e+00  3.571e+01  -0.182 0.855308    
## descriptionLight                 -3.893e+00  3.338e+01  -0.117 0.907219    
## descriptionMedium                -6.655e+00  3.868e+01  -0.172 0.863504    
## descriptionSunny                 -1.504e+01  3.725e+01  -0.404 0.686565    
## date                              1.353e-01  5.239e-03  25.822  < 2e-16 ***
## weather_impact:descriptionCloudy -3.218e-01  3.183e+00  -0.101 0.919538    
## weather_impact:descriptionHeavy   3.600e-01  3.448e+00   0.104 0.916909    
## weather_impact:descriptionLight  -5.373e-01  3.195e+00  -0.168 0.866521    
## weather_impact:descriptionMedium -3.276e-01  3.959e+00  -0.083 0.934093    
## weather_impact:descriptionSunny   6.436e-01  3.517e+00   0.183 0.854924    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 16.08 on 375 degrees of freedom
## Multiple R-squared:  0.7713, Adjusted R-squared:  0.7616 
## F-statistic: 79.06 on 16 and 375 DF,  p-value: < 2.2e-16
colors = c("actual" = "blue","predicted" = "red","residuals" = "gray50","zerorides" = "purple")
model = reduced_1_model
test_data = data %>% add_predictions(model = model) %>% add_residuals(model = model) %>% mutate(error = ifelse(abs(resid)>=20,"extreme","normal"))

As we can see excluding variables from model doesn’t make it worse residual st. error remains near 16.32, we can also use anova test function from stats package to check model variable significance. But firstly we would like to get best best model with possible minimum variables. For this purpose we can inspect p-value from model summary, it says how significant separate variable in model predictions, less p-value - more significant. So we would like to exclude snow, and combined term ow weather_impact and description out of model.

As we can see removing snow and separation of weather_impact and description, increased model quality with reducing residual standard error. Anova test between these two models also doesn’t show significant difference 0.983505 because p-value is 0.85>>0.05.

After few iterations we get to a model that contains only strictness of the policy restrictions, temperature and data. Represented model explains also explains most of the observations with relatively low residual standard error, but it is minimal for excluding, because anova significance difference between models without any of remaining predictors has p-value<0.05. So we get to our final model, that explains number of KeXi Rides using temperature, covid strictness level and date(positive growing trend).

reduced_3_model = lm(noRides ~ season+tavg+stringency+date,data = data)

summary(reduced_3_model)
## 
## Call:
## lm(formula = noRides ~ season + tavg + stringency + date, data = data)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -82.497  -8.774  -0.198   9.839  42.467 
## 
## Coefficients:
##                Estimate Std. Error t value Pr(>|t|)    
## (Intercept)  -2.463e+03  1.017e+02 -24.223  < 2e-16 ***
## seasonspring -3.487e+00  3.047e+00  -1.144 0.253264    
## seasonsummer -1.061e+01  2.883e+00  -3.679 0.000268 ***
## seasonwinter -4.068e+00  2.867e+00  -1.419 0.156644    
## tavg         -3.831e-01  1.932e-01  -1.983 0.048122 *  
## stringency   -1.310e-01  9.209e-02  -1.422 0.155807    
## date          1.369e-01  5.265e-03  26.002  < 2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 15.85 on 385 degrees of freedom
## Multiple R-squared:  0.772,  Adjusted R-squared:  0.7684 
## F-statistic: 217.2 on 6 and 385 DF,  p-value: < 2.2e-16
colors = c("actual" = "blue","predicted" = "red","residuals" = "gray50","zerorides" = "purple")
model = reduced_3_model
test_data = data %>% add_predictions(model = model) %>% add_residuals(model = model) %>% mutate(error = ifelse(abs(resid)>=20,"extreme","normal"))


ggplotly(ggplot(test_data %>% filter(year(date)>=2020)) +
  geom_point(aes(x = date,y = noRides,color = "actual"))+
  geom_point(aes(x = date,y = pred,color = "predicted"))+
  scale_color_manual(values = colors)+
  ggtitle("Final model fit"))
ggplotly(ggplot(test_data %>% filter(year(date)>=2020))+
            geom_line(aes(x = date,y = resid,color = "residuals"))+
            geom_ref_line(h = 0)+
            scale_color_manual(values = colors)+
            ggtitle("Residuals"))

After performing a minimal model we also want to check once again how residuals are distributed and some additional statistics metrics.

barplot <- ggplot(test_data, aes(x = resid ))+
  geom_histogram(aes(y = stat(density)),colour="black", fill="white", binwidth=9)+
  ggtitle("Final model residuals")

ggplotly(barplot)

We see normal distributed variable with skewness to the legt with 3 outliers at the left (analysis of individual days shows, that extremely low number of rides were when operator collecting data has changed so this is data specific problem that could be ignored or excluded from model)

test_data = test_data %>% filter(resid>=-50)
normal_dist = fitdistrplus::fitdist(test_data$resid,"norm")
plot(normal_dist)

So our residuals are normally distributed :)

Excluding more variables from a model doesn’t impove model as well increases residual error enormous, so we can make conclusion, that represented model is minimal fitting possible with variables that have most impact to number of rides by the weather. Remains only to check residuals of fitted model.

Conclusion

Performed LINEAR regression analysis shows, that there no strong correlations between number of rides and weather characteristics except of temperature, and temperature is also quite dependent from season, one difference between using season instead of the temperature is that relative temp changes in same season isn’t inspected, so it can be that relative fall of the temperature in summer also strongly impacts mobility. Also data was collected during covid-19 pandemie, so stringency-strictness is also significant by building an model. In the end date is used in the model, because there are positive growing trend with using KeXi ride service.